package servlet.admin;

import entity.Book_sort;
import net.sf.json.JSONObject;
import service.admin.BookSortService;
import service.admin.impl.BookSortServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * BookSortAddServlet
 *
 * @author 谭文斌
 * @since 2023/9/5
 */
@WebServlet("/admin/bookSortAddServlet")
public class BookSortAddServlet extends HttpServlet {
    BookSortService service = new BookSortServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf8");
        PrintWriter out = resp.getWriter();
        // 接受数据
        String name = req.getParameter("name");
        String description = req.getParameter("description");

        // 准备返回数据
        int code = 1;
        String msg = "";

        int row = service.getName(name);
        if (row > 0) {
            msg = "分类名称不能重复";
        } else {
            Book_sort book = new Book_sort(name, description);
            int add = service.add(book);
            if (add == 1) {
                code = 0;
                msg = "添加成功";
            } else {
                msg = "添加失败";
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        jsonObject.put("msg", msg);
        jsonObject.put("data", null);

        out.print(jsonObject.toString());
    }
}
